// 创建用户仓库
import { defineStore } from 'pinia'
// 引入接口
import {reqLogin} from '@/api/pms'
import { reqUserInfo } from '@/api/user'
// 引入数据类型
import type { loginForm, loginResponseData } from '@/api/user/type'
import type { UserState } from './types/type'
// import { RouteRecordRaw } from "vue-router";
// 引入路由（常量路由）
import { constantRoute } from '@/router/routes'
// 引入弹窗组件
import { ElMessage, ElMessageBox } from 'element-plus'
// 引入路由组件
import router from '@/router'
//截取第一个/之后的字符串
const subString = (str: string): string =>{
  if ( str && str !== '' ){
    const re = /\//;
    return str.replace(re,"")
  } else {
    return str
  }
}

import router from '@/router'

const useUserStore = defineStore('User', {
  // 存储数据的地方
  state: (): UserState => {
    return {
      hasRoute : false as boolean,//是否获取路由信息表标识
      menuRoutes: [],
      token: '', // 用户唯一标识
      refreshToken: '', // 更新token的标识
      username: '',
      avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
      userInfo: {}, // 用户信息
      roleInfo: {}, // 登录用户权限信息
      menuList: []  // 菜单信息
    }
  },
  // 异步|逻辑的地方
  actions: {
    // 用户登录
    async userLogin(data: loginForm) {
      const result: loginResponseData = await reqLogin(data)
      const { menuList, roleInfo, userInfo} = result
      // pinia|vuex数据存储其实是利用js对象
      // 存储用户信息、菜单信息、权限信息
      // if (userInfo && userInfo.dataPermissions && userInfo.dataPermissions.length > 0){
      if(userInfo){
          //用户信息
        this.setUserInfo(userInfo)
      }else {
        this.exit()
        ElMessage.error("该用户暂无数据权限，请联系管理员!")
        return Promise.reject()
      }
      if (menuList && menuList.length > 0){
        this.setMenuList(menuList)
      }else {
        this.exit()
        ElMessage.error("该用户暂无菜单权限，请联系管理员!")
        return Promise.reject()
      }
      //保存角色信息
      if (roleInfo){
        this.setRoleInfo(roleInfo)
      }else {
        this.exit()
        ElMessage.error("该用户暂无角色信息，请联系管理员!")
        return Promise.reject()
      }
    },
    // 获取登录用户信息
    async getUserInfo() {
      const result = await reqUserInfo()
      // 如果获取用户信息成功，存储用户信息
      if(result.code ===200) {
        this.username = result.data.checkUser.username
        this.avatar = result.data.checkUser.avatar
      }
    },
    // 添加token信息
    setToken(value: string) {
      this.token = value
    },
    // 添加refreshToken信息
    setRefreshToken (value: string) {
      this.refreshToken = value
    },
    setMenuList (value: []) {
      this.menuList = value
    },
    setRoleInfo (value: object) {
      this.roleInfo = value
    },
    setUserInfo (value: object) {
      this.userInfo = value
    },
    // 退出登录
    userLogout() {
      this.token = '';
      this.username = '';
      this.avatar = '';
    },
    // 添加路由信息
    async setMenuRoutes() {
      // router.removeRoute()
      this.menuRoutes = this.getRouter()
      await this.menuRoutes.forEach((route, idx) => {
        router.addRoute("main", route)
      })
      // 路由加载完成后动态添加进路由，否则刷新路由跳转404页面
      router.addRoute("main", {
        path: '/:pathMatch(.*)*',
        redirect: '/404',
        name: 'Any',
        meta: {
          title: '任意路由',
          hidden: true, // 路由标题在菜单中是否隐藏
          icon: 'Files',
        }
      })

    },
    //不需调用接口的退出 如token失效
    exit():void{
      // 清空缓存
      localStorage.clear()
      sessionStorage.clear()
      router.push( '/login' ).then( r  => {});
    },
    // 获取路由菜单信息
    getRouter(): any[] | undefined {
      let routerData = constantRoute
      let menuTemp: RouteRecordRaw[]
      if(this.menuList && this.menuList.length > 0) {
        const modules:any = import.meta.glob(`../../views/**/**.vue`);
        menuTemp = this.menuList.filter(menu => {
          return menu.funcType === 'M'
        }).map(menu => {
          let children = [];
          this.menuList.forEach(i => {
            if(i.funcType === 'F' && menu.funcMark.substring(0, 7) === i.funcMark.substring(0, 7)) {
              children.push({
                path : i.path,
                name : subString(i.path),
                meta : {
                  icon : i.icon ? i.icon : "guide",
                  title : i.name,
                  keepAlive : true
                },
                funcMark : i.funcMark,
                component: modules[`../../views/${i.component}.vue`]
              })
            }
          })
          return {
            path : menu.path,
            name : subString(menu.path),
            meta : {
              icon : menu.icon ? menu.icon : "guide",
              title : menu.name,
            },
            redirect: children[0].path,
            children,
            funcMark : menu.funcMark,
            component: () => import('@/layout/index.vue'),
          }
        })
        return [...routerData, ...menuTemp, {
          // 404
          path: '/404',
          name: '404',
          component: () => import('@/views/404.vue'),
          meta: {
            title: '404',
            hidden: true // 路由标题在菜单中是否隐藏
          },
        }]

      }else {
        ElMessageBox.alert('该用户暂无菜单权限，请联系管理员!', '警告', ).then(() => {
          //退出系统
          this.exit()
          return false
        })
      }


    }
  },
  getters: {},
  persist: [
    { key: 'token',storage:sessionStorage, paths: ['token']},
    { key: 'refreshToken', storage: localStorage,paths: ['refreshToken']},
    { key: 'userInfo',storage:sessionStorage,paths: ['userInfo','roleInfo']},
    { key: 'menuList',storage:sessionStorage,paths: ['menuList']},
    { key: 'roleInfo',storage:sessionStorage,paths: ['roleInfo']},
  ]
})

// 暴露仓库
export default useUserStore

